package com.yjj.im.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Base64;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Constant {


    /**
     * 资源共享文件KEY
     */
    private static String SharedPreferencesKey = "yjj_chengzhong";


    /**
     * 秤点位
     */
    public static final String clientname = "clientname";

    /**
     * web服务器地址
     */
    public static final String serverUrl = "curl";

    /**
     * mqtt topic
     */
    public static final String mqttTopic = "ctopic";




    /**
     * mqtt 服务器地址
     */
    public static final String mqttServer = "chost";
    /**
     * mqtt 服务器端口
     */
    public static final String mqttServerPort = "cport";
    /**
     * mqtt 用户名
     */
    public static final String mqttUser = "cuser";
    /**
     * mqtt 密码
     */
    public static final String mqttpassword = "cpw";
    /**
     * 当前登录用户名
     */
    public static final String currentUsername = "name";
    /**
     * 当前登录用户id
     */
    public static final String currentUserId = "id";
    /**
     * 当前登录用户id
     */
    public static final String currentisAuto = "isAudo";
    /**
     * 当前登录输入用户名
     */
    public static final String currentlogiUserName = "loginUserName";
    /**
     * 当前登录输入密码
     */
    public static final String currentLoginPassword = "loginPassword";
    /**
     * 当前登录记住密码
     */
    public static final String currentRemember = "loginRemember";



    /**
     * 获取存储信息
     *
     * @param context
     * @return
     */
    public static SharedPreferences getShare(Context context) {
        return context.getSharedPreferences(SharedPreferencesKey, Context.MODE_PRIVATE);
    }


    /**
     * 修改或添加存储参数
     *
     * @param paraMap 参数集合
     * @param context 上下文对象
     */
    public static void editSharedPreferences(HashMap<String, ? extends Object> paraMap, Context context) {
        Editor edit = getShare(context).edit();
        for (String key : paraMap.keySet()) {
            if (paraMap.get(key) instanceof String) {
                edit.putString(key, paraMap.get(key).toString());
            } else if (paraMap.get(key) instanceof Boolean) {
                edit.putBoolean(key, Boolean.parseBoolean(paraMap.get(key).toString()));
            } else {
                if (null == paraMap.get(key)) {
                    continue;
                }
                edit.putInt(key, Integer.parseInt(paraMap.get(key).toString()));
            }
        }
        edit.commit();
    }


    /**
     * 修改或添加单个参数(字符串类型)
     *
     * @param key     键
     * @param value   值
     * @param context 上下文对象
     */
    public static void editSharedPreferences(String key, String value, Context context) {
        Editor edit = getShare(context).edit();
        edit.putString(key, value);
        edit.commit();
    }

    /**
     * 修改或添加单个参数(数字类型)
     *
     * @param key     键
     * @param value   值
     * @param context 上下文对象
     */
    public static void editSharedPreferences(String key, int value, Context context) {
        Editor edit = getShare(context).edit();
        edit.putInt(key, value);
        edit.commit();
    }

    /**
     * 修改或添加单个参数(布尔类型)
     *
     * @param key     键
     * @param value   值
     * @param context 上下文对象
     */
    public static void editSharedPreferences(String key, boolean value, Context context) {
        Editor edit = getShare(context).edit();
        edit.putBoolean(key, value);
        edit.commit();
    }


    /**
     * 修改或添加单个参数(长整型)
     *
     * @param key     键
     * @param value   值
     * @param context 上下文对象
     */
    public static void editSharedPreferences(String key, long value, Context context) {
        Editor edit = getShare(context).edit();
        edit.putLong(key, value);
        edit.commit();
    }


    /**
     * 获取存储值(返回字符串类型)
     *
     * @param key 键
     * @return
     */
    public static String getSharedPreferencesValueByKeyString(Context context, String key) {
        return getShare(context).getString(key, "");
    }

    /**
     * 获取存储值(返回数字类型)
     *
     * @param key 键
     * @return
     */
    public static int getSharedPreferencesValueByKeyInt(Context context, String key) {
        return getShare(context).getInt(key, 0);
    }

    /**
     * 获取存储值(返回布尔类型)
     *
     * @param key 键
     * @return
     */
    public static boolean getSharedPreferencesValueByKeyBoolean(Context context, String key) {
        return getShare(context).getBoolean(key, false);
    }


    /**
     * 获取存储值(长整形)
     *
     * @param key 键
     * @return
     */
    public static long getSharedPreferencesValueByKeyLong(Context context, String key) {
        return getShare(context).getLong(key, 0);
    }




    /**
     * 登出
     *
     * @param context
     * @return
     */
    public static void loginOut(Context context) {
//        editSharedPreferences(Constant.userName, "", context);
//        editSharedPreferences(Constant.currentisAuto, "", context);
        Editor edit = getShare(context).edit();
        edit.clear();
    }




    /**
     * 获取登录用户ID
     *
     * @param context
     * @return
     */
    public static String getUserId(Context context) {
        return getSharedPreferencesValueByKeyString(context, Constant.currentUserId);
    }


    public static String getValue(Context context, String key) {
        return getSharedPreferencesValueByKeyString(context, key);
    }



    /**
     * 清除指定SharedPreferences信息
     */
    public static void removeSharedPreferences(Context context, String key) {
        getShare(context).edit().remove(key).commit();
    }


    /**
     * 清除SharedPreferences信息
     */
    public static void cleanSharedPreferences(Context context) {
        getShare(context).edit().clear().commit();
    }


    /**
     * 存储List集合
     *
     * @param context 上下文
     * @param key     存储的键
     * @param list    存储的集合
     */
    public static void putList(Context context, String key, List<? extends Serializable> list) {
        try {
            put(context, key, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取List集合
     *
     * @param context 上下文
     * @param key     键
     * @param <E>     指定泛型
     * @return List集合
     */
    public static <E extends Serializable> List<E> getList(Context context, String key) {
        try {
            return (List<E>) get(context, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 存储Map集合
     *
     * @param context 上下文
     * @param key     键
     * @param map     存储的集合
     * @param <K>     指定Map的键
     * @param <V>     指定Map的值
     */
    public static <K extends Serializable, V extends Serializable> void putMap(Context context,
                                                                               String key, Map<K, V> map) {
        try {
            put(context, key, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Map集合
     *
     * @param context 上下文
     * @param key     键
     * @param <K>     指定Map的键
     * @param <V>     指定Map的值
     * @return Map集合
     */
    public static <K extends Serializable, V extends Serializable> Map<K, V> getMap(Context context,
                                                                                    String key) {
        try {
            return (Map<K, V>) get(context, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 存储对象
     */
    public static void put(Context context, String key, Object obj) {
        if (obj == null) {//判断对象是否为空
            return;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            // 将对象放到OutputStream中
            // 将对象转换成byte数组，并将其进行base64编码
            String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            baos.close();
            oos.close();
            editSharedPreferences(key, objectStr, context);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取对象
     */
    public static Object get(Context context, String key) {
        String wordBase64 = getSharedPreferencesValueByKeyString(context, key);
        // 将base64格式字符串还原成byte数组
        if (TextUtils.isEmpty(wordBase64)) { //不可少，否则在下面会报java.io.StreamCorruptedException
            return null;
        }
        byte[] objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
        ObjectInputStream ois = null;
        Object obj = null;
        try {
            ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            obj = ois.readObject();
            bais.close();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

  /*
  * 16进制数字字符集
  */
          private static String hexString = "0123456789ABCDEF";
          private static String data = "0064FFFF621B001501000C0A000300FF0000000000000008003232323232323232E030";
  /*
  * 将字符串编码成16进制数字,适用于所有字符（包括中文）
  */
          public static String encode(String str) {
            // 根据默认编码获取字节数组
            byte[] bytes = data.getBytes();
              StringBuilder sb = new StringBuilder(bytes.length * 2);
            // 将字节数组中每个字节拆解成2位16进制整数
            for (int i = 0; i < bytes.length; i++) {
                 sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
                 sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
                }
            return sb.toString();
         }
  /*
  * 将16进制数字解码成字符串,适用于所有字符（包括中文）
  */
          public static String decode(String bytes) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(
                    data.length() / 2);
            // 将每2位16进制整数组装成一个字节
            for (int i = 0; i < data.length(); i += 2)
                 baos.write((hexString.indexOf(data.charAt(i)) << 4 | hexString
                       .indexOf(data.charAt(i + 1))));
            return new String(baos.toByteArray());
         }

         public static String toAscii(String str){
             StringBuilder hex = new StringBuilder();

             for (int i = 0; i < data.length(); i++) {
                 char ch = data.charAt(i);
                 int ascii = (int) ch;
                 String hexStr = Integer.toHexString(ascii);
                 hex.append(hexStr);
             }

             System.out.println("ASCII转换为16进制表示：" + hex.toString());
             return hex.toString();

         }

    // 转化十六进制编码为字符串
  public static String toStringHex1(String s) {
            byte[] baKeyword = new byte[data.length() / 2];
            for (int i = 0; i < baKeyword.length; i++) {
                 try {
                      baKeyword[i] = (byte) (0xff & Integer.parseInt(data.substring(
                                i * 2, i * 2 + 2), 16));
                     } catch (Exception e) {
                      e.printStackTrace();
                     }
                }
            try {
                 s = new String(baKeyword, "utf-8");// UTF-16le:Not
                } catch (Exception e1) {
                 e1.printStackTrace();
                }
            return s;
         }

}
